package com.fly.r2dbc.basics.service;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.fly.r2dbc.basics.dao.CustomerRepository;
import com.fly.r2dbc.basics.entity.Customer;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import reactor.core.publisher.Mono;

/**
 * @author Oliver Drotbohm
 */
@Component
@RequiredArgsConstructor
public class TransactionalService
{
    @NonNull
    private final CustomerRepository repository;
    
    /**
     * Saves the given {@link Customer} unless its firstname is "Dave".
     *
     * @param customer must not be {@literal null}.
     * @return
     */
    @Transactional
    public Mono<Customer> save(Customer customer)
    {
        return repository.save(customer).map(it -> {
            if (it.getFirstname().equals("Dave"))
            {
                throw new IllegalStateException();
            }
            else
            {
                return it;
            }
        });
    }
}
